﻿using CCWin.SkinControl;
using Modbus.Device;
using NPOI.XSSF.UserModel;
using Spire.Xls;
using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace DZ_Catcher
{
    public partial class Form1 : Form
    {
        public int BuadRate = 38400;
        private static SerialPort port;//= new SerialPort("COM3", BuadRate, Parity.None, 8, StopBits.One);
        private static ModbusSerialMaster master;// = ModbusSerialMaster.CreateRtu(port);
        public System.Timers.Timer timer = new System.Timers.Timer();
        public System.Data.DataTable dt = new System.Data.DataTable();

        //定义变量
        //static string DYunit, VFunit, VVFunit, GVFunit, TPunit, MFunit, MTunit, VOLunit;
        string[] comValue = new string[] { "质量流量", "质量总量", "体积流量", "体积总量", "温度",
                                                               "密度", "活零点", "驱动增益", "左侧线圈幅值", "右侧线圈幅值",
                                                               "原流量管频率", "传感器温度", "频率" ,"Delta T"};
        ushort[] MBaddr = new ushort[] { 246, 258, 252, 260, 250,
                                                              248, 292, 290, 378, 380,
                                                              284, 382,284,366};
        ushort[] addr = new ushort[10];//一次性读10个变量
        public static string Filepath, Savepath = null;
        public static int Saveflag = 0;
        public static string[] CatchText;
        public static bool ExcelSuc = false;

        #region  全部串口和可用串口切换
        private void button1_Click(object sender, EventArgs e)
        {
            skinComboBoxSerial.Items.Clear();
            for (int i = 0; i <= 16; i++)
            {
                skinComboBoxSerial.Items.Add("COM" + i);
            }
            skinComboBoxSerial.SelectedIndex = 0;
        }
        #endregion


        private void Form1_Load(object sender, EventArgs e)
        {
            //隐藏tabControl菜单栏 1
            tabControl1.ItemSize = new Size(0, 1); tabControl1.Appearance = TabAppearance.FlatButtons; tabControl1.SizeMode = TabSizeMode.Fixed;
        
            skinComboBoxSerial.Items.Clear();
            string[] str = SerialPort.GetPortNames();
            if (str.Length != 0)
            {
                for (int i = 0; i < str.Length; i++)
                {
                    skinComboBoxSerial.Items.Add(str[i]);
                }
                skinComboBoxSerial.SelectedIndex = 0;
            }
            else
            {
                button1_Click(sender, e);
            }
            skinComboBox4Buad.SelectedIndex = 3;
            skinComboBoxConfirm.SelectedIndex = 0;
            skinComboBoxBit.SelectedIndex = 1;
            skinComboBoxStop.SelectedIndex = 0;


            for (int i = 0; i < comValue.Length; i++)
            {
                Catch0.Items.Add(comValue[i]);
                Catch1.Items.Add(comValue[i]);
                Catch2.Items.Add(comValue[i]);
                Catch3.Items.Add(comValue[i]);
                Catch4.Items.Add(comValue[i]);
                Catch5.Items.Add(comValue[i]);
                Catch6.Items.Add(comValue[i]);
                Catch7.Items.Add(comValue[i]);
                Catch8.Items.Add(comValue[i]);
                Catch9.Items.Add(comValue[i]);
            }
            Catch0.SelectedIndex = 13;
            Catch1.SelectedIndex = 1;
            Catch2.SelectedIndex = 2;
            Catch3.SelectedIndex = 3;
            Catch4.SelectedIndex = 4;
            Catch5.SelectedIndex = 5;
            Catch6.SelectedIndex = 6;
            Catch7.SelectedIndex = 7;
            Catch8.SelectedIndex = 8;
            Catch9.SelectedIndex = 9;

        }

        private float ConvertDexToFloat(string a, string b)//读取两个寄存器的函数,先将两个十进制数转换为十六进制4位数,再连接起来转换为IEEE754数
        {
            int numA = int.Parse(a);
            int numB = int.Parse(b);

            // 转换为16进制
            string hexA = numA.ToString("X4");
            string hexB = numB.ToString("X4");
            if (hexA == "") { hexA = "0000"; }
            if (hexB == "") { hexB = "0000"; }

            //将A与B分割成1-2 3-4以便进行浮点字节转换
            string AfirstPart = hexA.Substring(0, 2);//1
            string AsecondPart = hexA.Substring(2, 2);//2
            string BfirstPart = hexB.Substring(0, 2);//3
            string BsecondPart = hexB.Substring(2, 2);//4

            // 组合成一个字符串
            string combined = FloatChange(AfirstPart, AsecondPart, BfirstPart, BsecondPart); ;//hexA + hexB;

            // 将其视作32位四字节单精度数
            uint num = uint.Parse(combined, System.Globalization.NumberStyles.AllowHexSpecifier);

            // 再进一步转换为十进制IEEE754浮点型数
            byte[] floatBytes = BitConverter.GetBytes(num);
            float result = BitConverter.ToSingle(floatBytes, 0);

            return result;
        }
        private string FloatChange(string a, string b, string c, string d)
        {
            int type = master.ReadInputRegisters(SlaAd, 520, 1)[0];//浮点字节顺序
            switch (type)//毫安输出源选择
            {
                case 0: return a + b + c + d;//"1-2 3-4"
                case 1: return c + d + a + b;//"3-4 1-2"
                case 2: return b + a + d + c;//"2-1 4-3"
                case 3: return d + c + b + a;//"4-3 2-1"
                default: return a + b + c + d;//"1-2 3-4";
            }

        }


        private void LinkButton_Click(object sender, EventArgs e)
        {

            CloseMessageBox();
            int Device = 0;
            try//检查连接参数输入的格式正确性
            {
                string com = skinComboBoxSerial.Text;
                int buadrate = int.Parse(skinComboBox4Buad.Text);
                Parity parity = (Parity)skinComboBoxConfirm.SelectedIndex;
                int databit = int.Parse(skinComboBoxBit.Text);
                StopBits stopbit = StopBits.One;
                switch (skinComboBoxStop.SelectedIndex)
                {
                    case 0:
                        stopbit = StopBits.One; break;
                    case 1:
                        stopbit = StopBits.Two; break;
                    default: break;
                }
                port = new SerialPort(com, buadrate, parity, databit, stopbit); // 初始化串口
                SlaAd = byte.Parse(skinTextBoxSladdr.Text); // 获取从站地址 
            }
            catch (Exception)
            { MessageBox.Show("请检查参数输入!", "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Error); port.Close(); return; }

            master = ModbusSerialMaster.CreateRtu(port); // 创建Modbus主站

            master.Transport.ReadTimeout = 1000; // 设置读取串口数据超时为 1000ms
            master.Transport.WriteTimeout = 300; // 设置写入串口数据超时为 300ms
            master.Transport.Retries = 2; // 设置重试次数为2次
            master.Transport.WaitToRetryMilliseconds = 200; // 设置重试间隔为200ms

            // 检查设备类型是否为0
                // 检查端口是否已经打开
                if (port.IsOpen == false)
                {
                    try { port.Open(); }
                    catch (Exception)
                    { MessageBox.Show("端口状态未连接或被占用中!", "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Error); port.Close(); return; }
                }
                try
                {
                    // 读取从站地址为SlaAd，起始地址为119，长度为1的输入寄存器
                    Device = master.ReadInputRegisters(SlaAd, 119, 1)[0];
                }
                catch (System.TimeoutException)
                { MessageBox.Show("请检查参数输入!", "No Device", MessageBoxButtons.OK, MessageBoxIcon.Error); port.Close(); return; }
                // 检查设备类型和从站地址是否和已有设备匹配
                if ((Device == 23))//传感器型号 MFT40
                { MessageBox.Show("找到型号:MFT40", "连接成功", MessageBoxButtons.OK, MessageBoxIcon.Information); port.Close(); tabControl1.SelectTab(1); return; }
                else if ((Device == 42))//传感器型号 MFT20
                { MessageBox.Show("找到型号:MFT20", "连接成功", MessageBoxButtons.OK, MessageBoxIcon.Information); port.Close(); tabControl1.SelectTab(1); return; }
                else
                { MessageBox.Show("请检查参数输入!", "No Device", MessageBoxButtons.OK, MessageBoxIcon.Error); port.Close(); return; }
            


            // 检查端口是否已经打开
            if (port.IsOpen == false)
            {
                try { port.Open(); }
                catch (Exception)
                { MessageBox.Show("端口状态未连接或被占用中!", "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Error); port.Close(); return; }
            }
            try
            {
                // 读取从站地址为SlaAd，起始地址为119，长度为1的输入寄存器
                Device = master.ReadInputRegisters(SlaAd, 119, 1)[0];
            }
            catch (System.TimeoutException)
            { MessageBox.Show("请检查连接设置!", "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Error); port.Close(); return; }

        }

        static public byte SlaAd = 1;

        public Form1()
        {
            InitializeComponent();
        }

        private void StartButton_Click(object sender, EventArgs e)
        {
            float time;
            dt.Rows.Clear();
            dt.Columns.Clear();

            addr[0] = MBaddr[Catch0.SelectedIndex];
            addr[1] = MBaddr[Catch1.SelectedIndex];
            addr[2] = MBaddr[Catch2.SelectedIndex];
            addr[3] = MBaddr[Catch3.SelectedIndex];
            addr[4] = MBaddr[Catch4.SelectedIndex];
            addr[5] = MBaddr[Catch5.SelectedIndex];
            addr[6] = MBaddr[Catch6.SelectedIndex];
            addr[7] = MBaddr[Catch7.SelectedIndex];
            addr[8] = MBaddr[Catch8.SelectedIndex];
            addr[9] = MBaddr[Catch9.SelectedIndex];

            bool hasDuplicate = (addr[0] == addr[1] || addr[0] == addr[2] || addr[0] == addr[3] || addr[0] == addr[4] || addr[0] == addr[5] || addr[0] == addr[6] || addr[0] == addr[7] ||
                                addr[1] == addr[2] || addr[1] == addr[3] || addr[1] == addr[4] || addr[1] == addr[5] || addr[1] == addr[6] || addr[1] == addr[7] ||
                                addr[2] == addr[3] || addr[2] == addr[4] || addr[2] == addr[5] || addr[2] == addr[6] || addr[2] == addr[7] ||
                                addr[3] == addr[4] || addr[3] == addr[5] || addr[3] == addr[6] || addr[3] == addr[7] ||
                                addr[4] == addr[5] || addr[4] == addr[6] || addr[4] == addr[7] ||
                                addr[5] == addr[6] || addr[5] == addr[7] ||
                                addr[6] == addr[7]);
            if (hasDuplicate == true)
            {
                MessageBox.Show("请勿选择相同数据!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            dt.Columns.Add(Catch0.Text, typeof(double));
            dt.Columns.Add(Catch1.Text, typeof(double));
            dt.Columns.Add(Catch2.Text, typeof(double));
            dt.Columns.Add(Catch3.Text, typeof(double));
            dt.Columns.Add(Catch4.Text, typeof(double));
            dt.Columns.Add(Catch5.Text, typeof(double));
            dt.Columns.Add(Catch6.Text, typeof(double));
            dt.Columns.Add(Catch7.Text, typeof(double));
            dt.Columns.Add(Catch8.Text, typeof(double));
            dt.Columns.Add(Catch9.Text, typeof(double));
            dt.Columns.Add("记录时间", typeof(string));

            time = float.Parse(skinTextBox1.Text);
            /*
            if (time < 5)
            {
                MessageBox.Show("采集间隔不可小于5秒!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            */
            CatchText = new string[] { Catch0.Text, Catch1.Text, Catch2.Text, Catch3.Text, Catch4.Text, Catch5.Text, Catch6.Text, Catch7.Text, Catch8.Text, Catch9.Text };
            // Using C# to execute dt = Reload(dt) at a set interval
            //System.Timers.Timer timer = ne59w System.Timers.Timer();
            timer.Interval = time * 1000; // seconds
            timer.Elapsed += (source, eventArgs) => { dt = Reload(dt); };
            timer.Start();
            skinLabel2.Visible = false;

            tabControl1.SelectTab(2);
            skinLabel1.Text = "正在采集:\r\n" + Catch0.Text + /*" " + Catch1.Text + "\r\n" + Catch2.Text + " " + Catch3.Text + "\r\n" + Catch4.Text + " " +
                                         Catch5.Text + "\r\n" + Catch6.Text + " " + Catch7.Text + "\r\n" + Catch8.Text + "\r\n" + Catch9.Text +*/
                                         "\r\n\r\n开始时间:\r\n" + DateTime.Now;
        }



        private System.Data.DataTable Reload(System.Data.DataTable datatable)
        {
            dt = new DataTable();
            dt = datatable;
            float[] value = new float[10];
            string Wrongname = "";
            try
            {
                if (port.IsOpen == false) { port.Open(); }
                /*
                for (int i = 0; i < 10; i++)
                {
                    Wrongname = CatchText[i];
                    value[i] = ConvertDexToFloat(master.ReadInputRegisters(SlaAd, addr[i], 2)[0] + "", master.ReadInputRegisters(SlaAd, addr[i], 2)[1] + "");
                }
                dt.Rows.Add(value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7], value[8], value[9], DateTime.Now);
                */
                    Wrongname = CatchText[0];
                    value[0] = ConvertDexToFloat(master.ReadInputRegisters(SlaAd, addr[0], 2)[0] + "", master.ReadInputRegisters(SlaAd, addr[0], 2)[1] + "");
                dt.Rows.Add(value[0],0,0,0,0,0,0,0,0,0, DateTime.Now);

            }
            catch (Exception)
            {
                MessageBox.Show("在"+DateTime.Now + "\r\n" + Wrongname + "的数据读取异常", "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
            }
            return dt;

        }

        private void Save_tabel(System.Data.DataTable dt)
        {
            timer.Stop();

            try
            {
                saveFileDialog1.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
                saveFileDialog1.Title = "Save File";
                saveFileDialog1.InitialDirectory = Environment.SpecialFolder.MyComputer.ToString();
                saveFileDialog1.FileName = "DZCatcher.xlsx";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    Filepath = saveFileDialog1.FileName;
                }
            }
            catch (Exception)
            { MessageBox.Show("请重新选择路径!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); }

            if (Filepath == null) { return; }

            //创建一个workbook实例
            Spire.Xls.Workbook wb = new Spire.Xls.Workbook();

            //清除默认的工作表
            wb.Worksheets.Clear();

            //添加一个工作表并指定表名
            Spire.Xls.Worksheet sheet = wb.Worksheets.Add("DZCatcher");

            //将DataTable数据写入工作表
            sheet.InsertDataTable(dt, true, 1, 1, true);
            sheet.Range["I1:J1"].Columns[0].ColumnWidth = 16F;
            sheet.Range["I1:J1"].Columns[1].ColumnWidth = 16F;
            sheet.Range["K1:K1"].Columns[0].ColumnWidth = 18F;

            try
            {
                //保存为.xlsx文件
                wb.SaveToFile(Filepath, Spire.Xls.ExcelVersion.Version2016);
                MessageBox.Show("Excel导出完成", "成功", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                ExcelSuc = true;
            }
            catch (Exception)
            { MessageBox.Show("未导出Excel\r\n请检查是否有已开进程", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }

            FileStream fs = new FileStream(Filepath, FileMode.Open, FileAccess.ReadWrite);
            XSSFWorkbook wbb = new XSSFWorkbook(fs);
            // 删除Sheet
            wbb.RemoveSheetAt(1);
            FileStream fileStream = new FileStream(Filepath, FileMode.Create, FileAccess.Write);
            wbb.Write(fileStream);

            for (int i = 0; i < 100; i++) { CloseMessageBox(); }

        }



        private void DrawChart(object sender, EventArgs e)
        {
            if (ExcelSuc == true)
            {
                try
                {
                    DrawChart("A");
                    DrawChart("B");
                    DrawChart("C");
                    DrawChart("D");
                    DrawChart("E");
                    DrawChart("F");
                    DrawChart("G");
                    DrawChart("H");
                    DrawChart("I");
                    DrawChart("J");
                    MessageBox.Show("折线图导出结束", "Over", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                catch (Exception)
                { MessageBox.Show("未导出折线图", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }
            }
        }


        private void DrawChart(string R)
        {
            // 加载Excel文件
            Workbook workbook = new Workbook();
            try
            {
                workbook.LoadFromFile(Filepath);
            }
            catch (Exception) { return; }
            Worksheet sheet = workbook.Worksheets[0];

            // 获取G2到非空的最后一个格子的数据
            int lastRow = sheet.LastRow;
            double[] data = new double[lastRow - 1];
            for (int i = 0; i < lastRow - 1; i++)
            {
                string cellValue = sheet.Range[R + (i + 2)].NumberText;
                if (double.TryParse(cellValue, out double value))
                {
                    data[i] = value;
                }
                else
                {
                    // Handle the case where the cell value is not a valid double
                    // For example, you can set data[i] to 0 or some default value
                    data[i] = 0;
                }
            }

            // 获取G1格的字符串作为表头
            string header = sheet.Range[R + "1"].Text;
            // 使用WinForms的Chart组件绘制折线图
            Form form = new Form();
            form.StartPosition = FormStartPosition.CenterScreen; // Center the form on the screen
            form.Size = new Size(1050, 620);
            form.Text = sheet.Range[R + "1"].Text;
            System.Windows.Forms.DataVisualization.Charting.Chart chart = new System.Windows.Forms.DataVisualization.Charting.Chart();
            chart.Parent = form;
            chart.Size = new Size(1000, 600);
            chart.ChartAreas.Add(new ChartArea());
            chart.Series.Add("Series" + R);
            chart.Series["Series" + R].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            double max;
            double min;
            bool maxLabelAdded;
            bool minLabelAdded;
            // Find the maximum and minimum values in the data array
            try
            {
                max = data.Max();
                min = data.Min();
                maxLabelAdded = false;
                minLabelAdded = false;
            }
            catch (Exception)
            { MessageBox.Show("未捕捉到足够生成折线图的有效值", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }

            // Add points to the chart series and label the maximum and minimum points with K column data
            for (int i = 0; i < lastRow - 1; i++)
            {
                chart.Series["Series" + R].Points.AddXY(i + 1, data[i]);
                if (data[i] == max && !maxLabelAdded)
                {
                    string kColumnData = sheet.Range["K" + (i + 2)].Text; // Get the K column data
                    chart.Series["Series" + R].Points[i].Label = $"(时间:{kColumnData}, 采集值:{data[i]})"; // Label the maximum point with K column data and y-coordinate
                    maxLabelAdded = true;
                }
                else if (data[i] == min && !minLabelAdded)
                {
                    string kColumnData = sheet.Range["K" + (i + 2)].Text; // Get the K column data
                    chart.Series["Series" + R].Points[i].Label = $"(时间:{kColumnData},采集值: {data[i]})"; // Label the minimum point with K column data and y-coordinate
                    minLabelAdded = true;
                }
            }
            chart.Series["Series" + R].Color = Color.Red;
            chart.Series["Series" + R].BorderWidth = 3;

            // 启用滚动和缩放
            chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
            chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
            chart.ChartAreas[0].CursorX.AutoScroll = true;
            chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
            chart.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true;
            chart.ChartAreas[0].AxisY.ScrollBar.IsPositionedInside = true;
            // 设置X轴和Y轴的箭头
            chart.ChartAreas[0].AxisX.ArrowStyle = AxisArrowStyle.Triangle;
            chart.ChartAreas[0].AxisY.ArrowStyle = AxisArrowStyle.Triangle;
            // 添加横轴和纵轴的注释
            chart.ChartAreas[0].AxisX.Title = "采集次数";
            chart.ChartAreas[0].AxisY.Title = header;
            // 设置X轴和Y轴的交叉点
            chart.ChartAreas[0].AxisX.Crossing = 0;
            chart.ChartAreas[0].AxisY.Crossing = 0;
            // 将除了横轴和纵轴之外的横竖线条更改为浅灰色
            chart.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.LightGray;
            chart.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.LightGray;
            chart.ChartAreas[0].AxisX.MinorGrid.LineColor = Color.LightGray;
            chart.ChartAreas[0].AxisY.MinorGrid.LineColor = Color.LightGray;


            form.Controls.Add(chart);
            if (Savepath == "Donotsave")
            {
                return;
            }
            else if (Saveflag == 1)
            {
                string filePath = Savepath + "\\" + sheet.Range[R + "1"].Text + ".png"; // 保存文件的路径
                chart.SaveImage(filePath, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png);
            }
            else
            {
                try
                {
                    folderBrowserDialog1.Description = "若需要生成折线图,请选择保存文件夹";
                    folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
                    folderBrowserDialog1.ShowNewFolderButton = true;
                    if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                    {
                        Savepath = folderBrowserDialog1.SelectedPath;
                        // 生成图表后保存为PNG格式
                        string filePath = Savepath + "\\" + sheet.Range[R + "1"].Text + ".png"; // 保存文件的路径
                        chart.SaveImage(filePath, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png);
                        Saveflag = 1;
                    }
                    else if (folderBrowserDialog1.ShowDialog() == DialogResult.Cancel)
                    {
                        Savepath = "Donotsave";
                    }
                }
                catch (Exception)
                { MessageBox.Show("请重新选择路径!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); }
            }
            //form.ShowDialog();
        }

        /// <summary>
        /// 重启按钮单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RestartButton_Click(object sender, EventArgs e)
        {
            Process process = Process.GetCurrentProcess();
            process.Close();

            Application.Restart();
        }



        // 查找窗口
        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        // 发送消息
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        // 关闭消息
        private const uint WM_CLOSE = 0x0010;


        private void CloseMessageBox()
        {
            // 查找并关闭MessageBox窗口
            IntPtr hwnd = FindWindow(null, "Error");//一致
            if (hwnd != IntPtr.Zero)
            {
                SendMessage(hwnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
        }

        private void Save_tabel(object sender, EventArgs e)
        {
            gifBox1.Visible = false;
            skinLabel2.Visible = true;
            Save_tabel(dt);

            DrawChart(sender, e);
            //skinButton1.Visible = false;
        }

    }
}
